<template>
  <a-row>
    <a-col :span="14">
      <a-input :disabled="isPreview" :type="type" v-model="value"></a-input>
    </a-col>
      <template v-if="isPreview">
        <a-col :offset="2" :span="3">
          <a-tooltip>
            <template slot="title">
              编辑
            </template>
            <a-icon type="edit" @click="isPreview = !isPreview" class="icon_style"/>
          </a-tooltip>
        </a-col>
      </template>
      <template v-else>
        <a-col :offset="2" :span="3">
          <a-tooltip>
            <template slot="title">
              保存
            </template>
            <a-icon type="save" @click="handleSave" class="icon_style"/>
          </a-tooltip>
        </a-col>
        <a-col :offset="2" :span="3">
          <a-tooltip>
            <template slot="title">
              取消
            </template>
            <a-icon type="stop" @click="handleCancel" class="icon_style"/>
          </a-tooltip>
        </a-col>
      </template>
  </a-row>
</template>

<script>
export default {
  name: 'PreviewAndEdit',
  props: {
    id: {
      required: true
    },
    defaultValue: {
      required: true
    },
    type: {
      default: 'text'
    },
    save: {
      type: Function,
      required: true
    }
  },
  data () {
    return {
      isPreview: true,
      value: null
    }
  },
  created () {
    this.isPreview = true
    this.value = this.defaultValue
  },
  methods: {
    handleSave () {
      const result = this.save(this.id, this.value)
      if (result) {
        this.$message.success('保存成功！')
        this.isPreview = !this.isPreview
        this.$emit('ok', this.value, this.record)
      } else {
        this.$message.success('保存失败！')
        this.handleCancel()
      }
    },
    handleCancel () {
      this.value = this.defaultValue
      this.isPreview = !this.isPreview
    }
  }
}
</script>
<style type="text/css" scoped>
.icon_style {
  margin-top: 6px;
  font-size: 18px;
}
</style>
